//文件上传：图片上传  1.安装multer  npm i multer -S

//2.引入
let multer = require("multer");
let express = require("express"); //绝对路径
let Router = express.Router(); //Router==app
let config = require("../../config.json");
let mongo = require("../../db/mongo");
let { ObjectId } = require("mongodb");
//3.配置存放路径：图片会存放在，站点根目录;优点：目录没有会自动创建;缺点：文件没有后缀，文件名被改写。
// var upload = multer({ dest: "uploads/" }); //以服务器文件为基准

var storage = multer.diskStorage({
  //设置存放文件路径:没有目录就上传失败
  //   destination: function (req, file, cb) {
  //     cb(null, "uploads/");
  //   },
  destination: "uploads/", //目录无则创建
  //设置文件名
  filename: function (req, file, cb) {
    //req请求对象信息；file：上传的文件对象；cb是一个修改文件名的回调
    // console.log(req, 111);
    // console.log(file, 222);
    let filename = file.originalname; //wzj.jpg
    let arr = filename.split("."); //['wzj','jpg']
    // cb(null, file.fieldname + "-" + Date.now());
    cb(null, arr[0] + "-" + Date.now() + "." + arr[1]); //加上时间戳，避免图片被覆盖
  },
});

var upload = multer({ storage: storage });

//4.使用multer模块实现文件的上传

/*
    图片的存储方式：
        * 第一种：把图片转成base64位，把字符串存到数据库里面。获取base64发给前端。前端获取到设置 src里面；(一般用在精灵图，小图);
        * 第二种:图片存在服务器里面。把绝对路径存入到数据库里面；把绝对路径给前端，前端就可以设置到 src里面。(这种方式最常用) http://localhost:2004/uploads/zql-1599446114024.jpg

*/

//上传头像
Router.post("/headphoto", upload.single("avatar"), async (req, res) => {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
  //   console.log(req.file, 111); //打印文件信息
  //   console.log(req.body, 222); //打印文件内容之外的普通文本信息
  let url = "http://localhost:" + config.PORT + "/";
  url = url + req.file.destination + req.file.filename; //路径已经拼接好，准备存入到数据库里面
  let query = {
    _id: ObjectId(req.body._id),
  };
  let newdata = {
    headphoto: url,
  };
  //更新数据库
  try {
    let data = await mongo.update("users", query, newdata);
    console.log(data);
  } catch (err) {}
  //   console.log(url);
  res.send("7788");
});

Router.post("/goodsimg", upload.array("photos", 3), (req, res) => {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
  console.log(req.files, 111);
  console.log(req.body, 222);
  res.send("67");
});

module.exports = Router; //导出主路由
